package com.ruoyi.web.controller.phone;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.base.AjaxResult;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExcelUtil;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.system.domain.Phone;
import com.ruoyi.system.domain.PhoneLabel;
import com.ruoyi.system.service.ExcelLogService;
import com.ruoyi.system.service.PhoneService;
import jxl.Workbook;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jsoup.helper.DataUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.UUID;


/**
 * 手机库管理
 */
@Controller
@RequestMapping("/phone")
public class PhoneController extends BaseController {

    private  ExcelUtil<Phone> excelUtil = new ExcelUtil(Phone.class);

    /**
     * 文件上传路径
     */
    @Value("${file.upload-path}")
    private String uploadpath;
    /**
     * excel 文件缓存路径
     */
    @Value("${file.excel-path}")
    private String excelPath;


    private static final Logger LOGGER = LoggerFactory.getLogger(PhoneController.class);

    private String prefix = "phone/";

    @Autowired
    private PhoneService phoneService;
    @Autowired
    private ExcelLogService excelLogService;

    /**
     * 手机号首页列表页展示
     * @return
     */
    @RequiresPermissions("phone:list:view")
    @GetMapping("/index")
    public String index(ModelMap mmap,HttpServletRequest req){
        String excelName = req.getParameter("excelName");
        Phone phone = new Phone();
        if(StringUtils.isNotEmpty(excelName))
            phone.setFlag(excelName);
        // 获取标签(全部)
        mmap.put("phone",phone);
        mmap.put("labels",phoneService.selectPhoneLabelData(null));
        return prefix + "/index";
    }

    /**
     * 文档管理
     * @param mmap
     * @return
     */
    @RequiresPermissions("phone:excelLog:view")
    @GetMapping("/excelLog")
    public String excelLog(ModelMap mmap){
        // 所有文件记录
        mmap.put("excelLogs",excelLogService.selectExcelLogData(null));
        return prefix + "/excel_log";
    }


    /**
     * 手机标签列表页展示
     * @return
     */
    @RequiresPermissions("phone:label:view")
    @GetMapping("/label")
    public String label(){
        return prefix + "/label";
    }


    /**
     * 手机号列表页数据
     * @param phone
     * @return
     */
    @RequiresPermissions("phone:phones:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Phone phone){
        startPage();
        List<Phone> list = phoneService.selectPhoneList(phone);
        return getDataTable(list);
    }

    /**
     * 标签列表
     * @param phoneLabel
     * @return
     */
    //@RequiresPermissions("phone:phones:list")
    @PostMapping("/label/list")
    @ResponseBody
    public TableDataInfo labelList(PhoneLabel phoneLabel){
        startPage();
        List<PhoneLabel> list = phoneService.selectPhoneLabelList(phoneLabel);
        return getDataTable(list);
    }

    @RequiresPermissions("phone:phones:importExp")
    @Log(title = "数据导入", businessType = BusinessType.INSERT)
    @PostMapping("/importExp")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult importExp(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        if (!file.isEmpty()) {

            try {
                Long currentTimeMillis = System.currentTimeMillis();

                // 导入文件缓存路径
                byte[] bytes = file.getBytes();
                Path path = Paths.get(uploadpath + currentTimeMillis+"_"+file.getOriginalFilename());
                Files.write(path,bytes);

                // 导入以及保存数据
                /*InputStream is = file.getInputStream();//获取输入流
                phoneService.writeExelData(is,file.getOriginalFilename());*/

                phoneService.writeExcelLargeData(path.toString(),file.getOriginalFilename());

                // 添加一个新标签
                PhoneLabel phoneLabel = new PhoneLabel();
                phoneLabel.setLabel(ExcelUtil.allFileName(file.getOriginalFilename()));
                phoneLabel.setRemark("导入文件时自动添加的标签");
                phoneService.insertPhoneLabel(phoneLabel);

            }catch (Exception e){e.printStackTrace();}
            return toAjax(Constants.TOAJAX_SUCCESS,"导入数据成功");
        }
        return  toAjax(Constants.TOAJAX_FAIL,"导入失败");
    }

    /**
     * 数据导出
     * @param response
     * @return
     */
    @RequiresPermissions("phone:phones:exportExp")
    @Log(title = "数据导出", businessType = BusinessType.INSERT)
    @PostMapping("/exportExp")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
        public AjaxResult exportExp( HttpServletResponse response) throws Exception{
        List<Phone> phones = phoneService.selectPhoneData(null);
        AjaxResult ajaxResult = this.createExcel(response,"手机号码库",phones);
        return  ajaxResult;
    }


    @Log(title = "添加标签", businessType = BusinessType.INSERT)
    @GetMapping("/addLabels")
    public String addLabels(HttpServletRequest req,ModelMap mmap){
        Phone pho = ReqPhone(req);
        // 获取 需要添加标签的个数

        // 传入 phone 对象
        mmap.put("phone",pho);
        // 获取标签(全部)
        mmap.put("labels",phoneService.selectPhoneLabelData(null));
        return prefix + "/add_label";
    }

    /**
     * 添加标签 add
     * @return
     */
    @GetMapping("/add")
    public String add(){
        return prefix + "/add";
    }
    /**
     * 添加标签 add
     * @return
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id,ModelMap mmap){
        mmap.put("phoneLabel",phoneService.getEntityById(id));
        return prefix + "/edit";
    }

    /**
     * 新增标签
     */
    @RequiresPermissions("phone:phones:add")
    @Log(title = "新增标签", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult addSave(PhoneLabel phoneLabel){
        return toAjax(phoneService.insertPhoneLabel(phoneLabel));
    }

    /**
     * 编辑标签
     */
    @RequiresPermissions("phone:phones:edit")
    @Log(title = "编辑标签", businessType = BusinessType.INSERT)
    @PostMapping("/edit")
    @Transactional(rollbackFor = Exception.class)
    @ResponseBody
    public AjaxResult editSave(PhoneLabel phoneLabel){
        return toAjax(phoneService.updatePhoneLabel(phoneLabel));
    }

    /**
     * 删除标签
     * @param ids
     * @return
     */
    @RequiresPermissions("phone:phones:remove")
    @Log(title = "删除标签", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids){
        try{
            return toAjax(phoneService.removePhoneLabel(ids));
        } catch (Exception e){ return error(e.getMessage()); }
    }

    /**
     * 添加标签
     * @return
     */
    @PostMapping("/addFlags")
    @ResponseBody
    public AjaxResult addFlags(HttpServletRequest req){
        String flags = req.getParameter("flags");

        if(StringUtils.isNotEmpty(flags)){

            Phone pho = ReqPhone(req);
            flags += ","; // 后面加上那个一个 逗号

            // 获取需要添加标签的 List<Phone>
            List<Phone> phone = phoneService.selectPhoneData(pho); // 无条件，查询出全部的
            phoneService.updateBatchFlag(flags,phone);
            return toAjax(Constants.TOAJAX_SUCCESS,"添加标签成功");
        }
        return toAjax(Constants.TOAJAX_FAIL);
    }

    /**
     * 整理数据（重复的数据整合成一条--主要是标签）
     * @return
     */
    @PostMapping("/arrangeDatas")
    @ResponseBody
    private AjaxResult arrangeDatas(){
        return toAjax(Constants.TOAJAX_SUCCESS);
    }


    private Phone ReqPhone(HttpServletRequest req){
        Phone pho = new Phone();
        String phone = req.getParameter("phone");
        String flag = req.getParameter("flag");
        String craBeginTime = req.getParameter("craBeginTime");
        String craEndTime = req.getParameter("craEndTime");

        if(StringUtils.isNotEmpty(phone)) pho.setPhone(Long.valueOf(phone));
        pho.setFlag(flag);
        pho.setCraBeginTime(craBeginTime);
        pho.setCraEndTime(craEndTime);
        return pho;
    }


    public AjaxResult createExcel(HttpServletResponse response,String sheetName,List<Phone> phones) throws Exception {
        //String title[] = { "手机号码" };

        // 以导出的时间命名
        //String filename = DateUtils.dateTimeNow() + ".xls";
        String filename = "-"+ DateUtils.dateTimeNow() + ".xls";

        WritableWorkbook book = Workbook.createWorkbook(new File(excelPath + filename));

        // 生成名为“第一页”的工作表，参数0表示这是第一页
        WritableSheet sheet = book.createSheet("客户资源调查", 0);
        // 设置列宽
        sheet.getSettings().setDefaultColumnWidth(13);
        // 设置行高
        sheet.getSettings().setDefaultRowHeight(400);
        // 设置字体
        WritableFont titleColor = new WritableFont(WritableFont.ARIAL, 12, WritableFont.BOLD, false,
                UnderlineStyle.NO_UNDERLINE, Colour.RED);
        WritableCellFormat titleFormat = new WritableCellFormat(titleColor);
        // 设置背景色
        titleFormat.setBackground(Colour.LIGHT_GREEN);
        // 添加表头
        /*for (int i = 0; i < title.length; i++) { // title
            sheet.addCell(new Label(i, 0, title[i], titleFormat));
        }*/
        // 写入内容
        for (int i = 0; i < phones.size(); i++){
            sheet.addCell(new Label(0, i, phones.get(i).getPhone().toString()));
        }
        // 写入数据
        book.write();
        // 关闭文件
        book.close();
        return AjaxResult.success(filename);
    }



    @PostMapping("/deleteData")
    @ResponseBody
    public AjaxResult deleteData(HttpServletRequest req){
        String prefixExcelName = req.getParameter("prefixExcelName");
        String id = req.getParameter("id");
        return toAjax(phoneService.removePhoneByFlag(prefixExcelName,Long.valueOf(id)));
    }

}
